﻿using D.Medicalcare.Infrastructure.Interfaces;
using Microsoft.EntityFrameworkCore;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace D.Medicalcare.Infrastructure.Implement
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    {

        private readonly MyDbContext db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">参数</param>

        public BaseRepository(MyDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 插入记录
        /// </summary>
        /// <param name="entity">参数</param>
        /// <returns></returns>
        public async Task<int> AddAsync(T entity)
        {
            await db.Set<T>().AddAsync(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量插入记录
        /// </summary>
        /// <param name="entities">参数</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> AddRangeAsync(List<T> entities)
        {
            await db.Set<T>().AddRangeAsync(entities);

            return await db.SaveChangesAsync();
        }

        public Task<int> DelRange(List<T> t)
        {
            db.Set<T>().RemoveRange(t);
            return db.SaveChangesAsync();
        }

        public IQueryable<T> GetAll()
        {
            return db.Set<T>().AsQueryable();   
        }


        /// <summary>
        /// 更新记录
        /// </summary>
        /// <param name="entity">参数</param>
        /// <returns></returns>
        public async Task<int> Update(T entity)
        {
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }

        public async Task<T> GetModel(int t)
        {
            return await db.Set<T>().FindAsync(t);
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> UpdateRang(IEnumerable<T> entities)
        {
            db.Set<T>().UpdateRange(entities);
            return await db.SaveChangesAsync();
        }
    }
}
